﻿
/***************************************************************************

Copyright (c) BizRulX. All rights reserved.

***************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio;
using System.Runtime.InteropServices;

namespace RuleXSoft.RulXCodeGenerator
{
    public class VSEnvUtility
    {
        public static EnvDTE.Project GetSelectedProjectHierarchyInstance()
        {
            IVsHierarchy hierarchy = null;
            IntPtr hierarchyPtr = IntPtr.Zero;
            IntPtr selectionContainer = IntPtr.Zero;
            uint itemid;
            string currentDocument;


            // Retrieve shell interface in order to get current selection
            IVsMonitorSelection monitorSelection = Package.GetGlobalService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
            if (monitorSelection == null)
                throw new InvalidOperationException();

            try
            {
                // Get the current project hierarchy, project item, and selection container for the current selection
                // If the selection spans multiple hierachies, hierarchyPtr is Zero
                IVsMultiItemSelect multiItemSelect = null;
                ErrorHandler.ThrowOnFailure(
                    monitorSelection.GetCurrentSelection(
                        out hierarchyPtr, out itemid,
                        out multiItemSelect, out selectionContainer));

                // We only care if there is only one node selected in the tree
                if (!(itemid == VSConstants.VSITEMID_NIL ||
                    hierarchyPtr == IntPtr.Zero ||
                    multiItemSelect != null ||
                    itemid == VSConstants.VSITEMID_SELECTION))
                {
                    hierarchy = Marshal.GetObjectForIUnknown(hierarchyPtr)
                        as IVsHierarchy;
                }

                uint itemId;
                object objProj;
                int hr = hierarchy.GetCanonicalName(itemid, out currentDocument);
                hierarchy.ParseCanonicalName(currentDocument, out itemId);

                hierarchy.GetProperty((uint)VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out objProj);
                EnvDTE.Project dteProject = (EnvDTE.Project)objProj;



                return dteProject;
            }
            finally
            {
                if (hierarchyPtr != IntPtr.Zero)
                    Marshal.Release(hierarchyPtr);
                if (selectionContainer != IntPtr.Zero)
                    Marshal.Release(selectionContainer);
            }
        }
    }
}
